package swu.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter(urlPatterns = {"/client/*","/administrator/*"})
public class VeriFilter implements Filter
{

    public final  static String LOGIN_TAG = "LOGIN_TAG";
    public final  static String LOGIN_SUCCESS = "LOGIN_TAG_SUCCESS";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    {
        HttpSession session = ((HttpServletRequest) request).getSession(true);
        Object tag = session.getAttribute(LOGIN_TAG);

        if (tag == null || !tag.equals(LOGIN_SUCCESS))
        {
            ((HttpServletResponse) response).sendRedirect("/shopping-mall/index.html");
            return;
        }
        else
        {
            chain.doFilter(request, response);
        }
    }

}
